package com.deng.mina.common.protocol;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;

/**
 * @Project
 * @Module
 * @JDK_Vserion 1.8
 * @Author DengLibin
 * @Email dlb@smarthse.cn
 * @Desc 编码器
 * @since 2019/9/18 0018 9:46
 */
public class ProtocolEncoder extends ProtocolEncoderAdapter {
    private Charset charset;
    public  ProtocolEncoder(Charset charset){
        this.charset = charset;
    }
    /**
     * 编码
     * @param session
     * @param message
     * @param out
     * @throws Exception
     */
    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        ProtocolPack pack = (ProtocolPack)message;  // 数据包对象
        // 创建缓冲区
        IoBuffer buf = IoBuffer.allocate(pack.getLength());
        buf.setAutoExpand(true);// 自动增长
        buf.putInt(pack.getLength());// 包大小
        buf.put(pack.getFlag()); // 标识信息
        if(pack.getContent() != null){
            buf.put(pack.getContent().getBytes(charset)); // 数据内容
        }
        buf.flip();
        out.write(buf);
    }
}
